import string
import sys

sys.path.append("..")
from flask import Blueprint, jsonify, request, send_from_directory
from models import User, DoTask
from exts import db

bp = Blueprint("manage", __name__, url_prefix="/manage")


@bp.route("/worker_tasks", methods=["POST", "GET"])
def worker_tasks():
    # 获取前端post请求发送来的数据(username,email)
    # 为了获取猎人已领取的任务
    params = request.get_json()  # {'email': '123@qq.com', 'username': '406973249'}
    user_item = User.query.filter_by(email=params["email"]).first()
    if user_item.username == params["username"]:
        do_tasks = DoTask.query.filter_by(worker_id=user_item.id).all()
        task_data = []
        for do_task in do_tasks:
            task_data_item = {
                "key": do_task.id,
                "tasktitle": do_task.task.tasktitle,
                "bounty": do_task.task.bounty,
                "enddate": do_task.task.enddate,
                "task_res": [do_task.task_res],
                "email": do_task.task.user.email,  # 猎人用户，返回雇主的email
                "taskintro": do_task.task.taskintro,
                "type_name": do_task.task.tasktype.typename,
                "task_evi": do_task.task_evi
            }
            task_data.append(task_data_item)
        # print(task_data)
        return jsonify({"msg": "请求成功", "task_data": task_data})
    else:
        return "用户不存在", 400


@bp.route("/change_worker_task_res", methods=["POST", "GET"])
def change_worker_task_res():
    # 修改用户任务状态接口
    params = request.get_json()  # {'id': 21, 'res': 0}
    dotask_item = DoTask.query.filter_by(id=params["id"]).first()
    if dotask_item is None:
        return "参数错误", 400

    if dotask_item.task_res == params["res"] and params["res"] != 1 and params["res"] != 2:
        dotask_item.task_res = 1
        db.session.commit()
        return "修改成功"
    else:
        return "错误请求", 400


@bp.route("/give_up_worker_task", methods=["POST", "GET"])
def give_up_worker_task():
    # 用户放弃任务
    # 实现逻辑是do_task删除对应数据，tasks表token改为0(待领取)
    params = request.get_json()  # {'id': 28, 'res': 1}
    dotask_item = DoTask.query.filter_by(id=params["id"]).first()
    # 如果查询不到该任务，则返回错误
    if dotask_item is None:
        return "参数错误", 400

    if dotask_item.task_res != 2 and dotask_item.task_res in [0, 1, 2] and dotask_item.task_res == params["res"]:
        dotask_item.task.taken = 0  # 改为未领取状态
        db.session.delete(dotask_item)  # 删除do_task对应的数据
        db.session.commit()
        return "任务放弃成功，望下次执行任务成功"
    else:
        return "参数错误", 400


@bp.route("/upload_task_evi", methods=["POST", "GET"])
def upload_task_evi():
    # 接收用户提交的作证材料
    upload_file = request.files["TaskEviFile"]  # 获得文件
    dotask_id = request.form["dotask_id"]  # 获得do_task表中的id
    user_email = request.form["email"]  # 获得当前用户的email，用于验证该任务是否为该用户提交的验证

    dotask_item = DoTask.query.filter_by(id=dotask_id).first()
    # 如果查询不到该任务，则返回错误
    if dotask_item is None:
        return "参数错误", 400

    worker_item = User.query.filter_by(id=dotask_item.worker_id).first()  # 获得猎人的信息
    if worker_item.email != user_email:
        return "不是该任务的猎人", 400

    file_name = upload_file.filename
    file_path = "./public/task_evi/" + str(dotask_item.task_id) + dotask_item.task.tasktitle + "." + \
                file_name.split(".")[-1]
    upload_file.save(file_path)
    dotask_item.task_evi = file_path
    db.session.commit()
    return "上传成功"


# 测试
@bp.route("/download_task_evi_1", methods=["POST", "GET"])
def test():
    return send_from_directory("./public/task_evi/", "38.docx", as_attachment=True)
